package com.duoec.dw.lineage.service.impl.analyser.statement;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlRenameTableStatement;
import com.duoec.dw.lineage.dto.DdlChangeDto;
import com.duoec.dw.lineage.dto.DdlChangeItemDto;
import com.duoec.dw.lineage.enums.DdlChangeTypeEnum;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author xuwenzhen
 */
@Service
public class MySqlRenameTableStatementAnalyser extends BaseStatementAnalyser<MySqlRenameTableStatement, String> {
    /**
     * 获取当前分析器分析的statement类型
     *
     * @return statement类型
     */
    @Override
    public Class<MySqlRenameTableStatement> getType() {
        return MySqlRenameTableStatement.class;
    }

    /**
     * 解析语句
     *
     * @param statement SQL语句
     * @return 返回值
     */
    @Override
    public String analyse(MySqlRenameTableStatement statement) {
        List<MySqlRenameTableStatement.Item> tableSources = statement.getItems();
        if (CollectionUtils.isEmpty(tableSources)) {
            return null;
        }

        MySqlRenameTableStatement.Item tableSource = tableSources.get(0);
        return AnalyserUtils.formatFieldName(tableSource.getName().getSimpleName());
    }

    /**
     * 处理解析结果
     *
     * @param dto       DdlChangeDto实例
     * @param tableName 语句的处理结果
     */
    @Override
    public void setResult(DdlChangeDto dto, String tableName) {
        dto.setTableName(tableName);
        DdlChangeItemDto item = new DdlChangeItemDto();
        item.setChangeType(DdlChangeTypeEnum.RENAME_TABLE.getType());
        dto.getItems().add(item);
    }
}
